package com.adinnet.core.weiMsg;

import com.adinnet.common.utils.PropertiesConfig;
import com.adinnet.core.redis.RedisService;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/4 0004.
 */
@Component
public class WX_TokenUtil {

    private static Logger log = LoggerFactory.getLogger(WX_TokenUtil.class);

    private static RedisService redisService;

    @Autowired
    public WX_TokenUtil(RedisService redisService) {
        WX_TokenUtil.redisService = redisService;
    }
    /**
     * 手动让AccessToken失效
     * @return
     */
    public static AccessToken invalidToken(){
        redisService.remove("wx_access_token");
        return getWXToken();
    }

    /**
     *  获得微信 AccessToken
     * access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
     * 开发者需要access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取
     * 的access_token失效。
     * （此处我是把token存在Redis里面了）
     */
    public static AccessToken getWXToken() {
        AccessToken access_token = new AccessToken();
        if (redisService.exists("wx_access_token")) {
            access_token.setAccess_token(redisService.getString("wx_access_token"));
            return access_token;
        }

        String tokenUrl =  PropertiesConfig.weiXinGetTokenUrl+"?grant_type=client_credential&appid="+ PropertiesConfig.weiXinSmallProgramId +"&secret="+  PropertiesConfig.weiXinSmallSecret;
        JSONObject jsonObject = WX_HttpsUtil.httpsRequest(tokenUrl, "GET", null);
        System.out.println("jsonObject:"+jsonObject);

        if (null != jsonObject) {
            try {
                access_token.setAccess_token(jsonObject.getString("access_token"));
                access_token.setExpiresin(jsonObject.getInteger("expires_in"));
                redisService.set("wx_access_token",jsonObject.getString("access_token"),jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                access_token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }

        return access_token;
    }


    public static Map<String,String> getWebToken(String code) {
        Map<String,String> map = new HashMap<>();
        String tokenUrl =  "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code&appid="+ PropertiesConfig.weiXinSmallProgramId +"&secret="+  PropertiesConfig.weiXinSmallSecret+"&code="+code;
        JSONObject jsonObject = WX_HttpsUtil.httpsRequest(tokenUrl, "GET", null);
        System.out.println("jsonObject:"+jsonObject);
        if (null != jsonObject) {
            try {
                map.put("accessToken",jsonObject.getString("access_token"));
                map.put("openid",jsonObject.getString("openid"));
            } catch (JSONException e) {
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return map;
    }
}
